package com.hexu.event.util;


import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {

    //private static Properties properties = new Properties();

    //静态代码块，加载注册驱动，随类只加载一次
    static {

        try {
            //读取路径
           // properties.load(new BufferedReader(new FileReader("C:\\java learning\\hexu_event02\\src\\com\\hexu\\event\\resource")));
            //String driver = properties.getProperty("driver");
            String driver = "com.mysql.cj.jdbc.Driver";
            Class.forName(driver);
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    //@return返回连接对象
    //利用Properties中的getProperty（"名"）获取配置文件中的值
    public static Connection getConn() {
        try {
            //String url = properties.getProperty("url");
            //String username = properties.getProperty("username");
            //String password = properties.getProperty("password");
            String url = "jdbc:mysql://localhost:3306/national_health_service?serverTimezone=GMT%2B8";
            String username = "root";
            String password = "1314520";

            return DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取数据库失败了！", e);
        }
    }

    /**
     * @param conn 关闭连接对象
     * @param ps  关闭预编译对象
     * @param rs  关闭结果集
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null)
                        conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

